package presentation;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.EmpresaPrivada;
import domain.EmpresaPublica;

/**
 * Servlet implementation class for Servlet: MontarEmpresaEnSesion
 *
 */
 public class MontarEmpresaEnSesion extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public MontarEmpresaEnSesion() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String pub = (String)request.getParameter("pub");
		String cif = (String)request.getParameter("cif");
		String pass = (String)request.getParameter("pass");
		HttpSession sesion = request.getSession(); 
		String resource = "./error/error.jsp";
		
		if(pub==null){
			EmpresaPrivada ep = new EmpresaPrivada(cif,pass);
			sesion.setAttribute("session.cif", ep.getCif());
			sesion.setAttribute("session.nombre", ep.getNombre());
			sesion.setAttribute("session.id", ep.getId());
			resource = "./EmpresaPrivada/entrada.jsp";
		}else{
			EmpresaPublica ep = new EmpresaPublica(cif,pass); 
			sesion.setAttribute("session.cif", ep.getCif());
			sesion.setAttribute("session.nombre", ep.getNombre());
			sesion.setAttribute("session.id", ep.getId());
			resource = "./EmpresaPublica/entrada.jsp";
		}
		
		
		RequestDispatcher d = request.getRequestDispatcher(resource);
		if(d!=null){
			d.forward(request,response);
		}
	}
}